package com.example.weather_plus;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.example.weather_plus.data.model.DailyWeatherForecast;
import com.example.weather_plus.data.model.HourlyWeatherForecast;
import com.example.weather_plus.databinding.ActivityMainBinding;
import com.example.weather_plus.ui.weatherforecast.adapter.HourlyForecastAdapter;
import com.example.weather_plus.ui.weatherforecast.adapter.WeatherForecastAdapter;
import com.example.weather_plus.ui.weatherforecast.adapter.layoutmanager.NonScrollableLinearLayoutManager;
import com.example.weather_plus.ui.weatherforecast.viewmodel.GeoViewModel;
import com.example.weather_plus.ui.weatherforecast.viewmodel.WeatherViewModel;
import com.example.weather_plus.ui.weathergram.view.DiaryActivity;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.tencent.smtt.sdk.QbSdk;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import cn.bmob.v3.Bmob;

public class MainActivity extends AppCompatActivity {

    private static final int REQUEST_LOCATION_PERMISSION = 100;
    ActivityMainBinding binding;
    WeatherViewModel viewModel;
    GeoViewModel geo_viewModel;
    AMapLocationClientOption option = new AMapLocationClientOption();
    public AMapLocationClient locationClient = null;

    private HourlyForecastAdapter hourly_adapter;
    CoordinatorLayout main;
    TextView city_tv, temp_now_tv, max_tv, min_tv, weather_tv, aqi_tv, aqi_cond_tv, test;
    WebView aqi_map;
    RecyclerView hourly_recyclerView, daily_recyclerView;
    ProgressBar pgb;
    FloatingActionButton weathergram_fab;

    String aqi_map_url = null;
    String old_locate;
    LinearLayoutManager layoutManager;
    List<HourlyWeatherForecast> previousForecasts;


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        aqi_map = binding.apimapWebView;
        city_tv = binding.city;
        temp_now_tv = binding.temp;
        max_tv = binding.max;
        min_tv = binding.min;
        weather_tv = binding.weather;
        aqi_tv = binding.tvAqiValue;
        aqi_cond_tv = binding.aqiCond;
        pgb = binding.pbAqiProgress;
        test = binding.testTv;
        main = binding.main;
        weathergram_fab = binding.floatingActionButton;

        viewModel = new ViewModelProvider(this, new ViewModelProvider.AndroidViewModelFactory(getApplication())).get(WeatherViewModel.class);
        geo_viewModel = new ViewModelProvider(this, new ViewModelProvider.AndroidViewModelFactory(getApplication())).get(GeoViewModel.class);

        // Bmob初始化
        Bmob.initialize(this, "19bdb825482950b3e89dca5b0d23b3cf");

        /*
         * 初始化腾讯X5 WebView服务
         */
        QbSdk.initX5Environment(getApplicationContext(), new QbSdk.PreInitCallback() {
            @Override
            public void onCoreInitFinished() {
                // X5内核初始化完成回调
            }

            @Override
            public void onViewInitFinished(boolean result) {
                // WebView初始化完成回调
            }
        });


        // 腾讯X5 webview 启用JavaScript支持
        WebSettings webSettings = aqi_map.getSettings();
        webSettings.setJavaScriptEnabled(true); // 启用JavaScript支持

        // 可选：允许访问文件URL以及其他安全设置
        webSettings.setAllowFileAccess(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setLoadsImagesAutomatically(true);
        aqi_map.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                // 返回false表示网页在当前WebView中加载，不跳转到外部浏览器
                return false;
            }
        });

        /*
         * 初始化高德定位sdk
         */

        // 请求定位权限
        requestLocationPermission();

        // 关键的两行代码 兼容最新版本
        // 强制同意高德地图sdk隐私协议
        AMapLocationClient.updatePrivacyShow(this, true, true);
        AMapLocationClient.updatePrivacyAgree(this, true);

//        String apiKey = "YOUR_API_KEY"; //TODO 应从安全的地方获取API密钥，如SecurePreferences

        // 日内天气预报
        hourly_recyclerView = binding.recyclerView;
        hourly_recyclerView.setHasFixedSize(true);
        layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        hourly_recyclerView.setLayoutManager(layoutManager);

        // 当前天气状况
        viewModel.getCurrentWeather().observe(this, repo -> {
            if (repo != null) {
                temp_now_tv.setText(repo.getNow().getTemp() + "°");
                weather_tv.setText(repo.getNow().getText());

                String text = repo.getNow().getText();
                int hour = repo.getNow().getObsTime().getHours();

                Drawable drawable = ContextCompat.getDrawable(this, R.drawable.rain);
                main.setBackground(drawable);

//                if(text.equals("晴")){
//                    if(hour> 4 && hour < 18){
//                        Drawable drawable = ContextCompat.getDrawable(this, R.drawable.sunnybgl);
//                        main.setBackground(drawable);
//                    }
//                    else{
//                        Drawable drawable = ContextCompat.getDrawable(this, R.drawable.sunny_night_bg);
//                        main.setBackground(drawable);
//                    }
//                }

            } else {
                Log.e("WeatherView", "Received null WeatherInfo");
            }
        });

        daily_recyclerView = binding.forecastRecyclerView;
        NonScrollableLinearLayoutManager non_layoutManager = new NonScrollableLinearLayoutManager(this,LinearLayoutManager.VERTICAL,false);
        daily_recyclerView.setLayoutManager(non_layoutManager);

        viewModel.getDailyWeatherForecast().observe(this, post -> {
            if (post != null) {
                // 更新视图
//                tv.setText(post.getDaily().get(0).getCloud());
                max_tv.setText(post.getDaily().get(0).getTempMax() + "°");
                min_tv.setText(post.getDaily().get(0).getTempMin() + "°");


                List<DailyWeatherForecast> forecasts = post.getDaily();
                WeatherForecastAdapter adapter = new WeatherForecastAdapter(forecasts);
                daily_recyclerView.setAdapter(adapter);

            } else {
                // 处理错误情况
                Log.e("WeatherView", "Received null WeatherInfo");
            }
        });

        hourly_adapter = new HourlyForecastAdapter(this, new ArrayList<>()); // 初始化Adapter
        hourly_recyclerView.setAdapter(hourly_adapter);

        viewModel.getHourlyForecast().observe(this, post -> {
            if (post != null) {

                List<HourlyWeatherForecast> dailyForecasts = post.getHourly();
                hourly_adapter.updateData(dailyForecasts); // 更新数据，而不是重新设置Adapter

            } else {
                // 处理错误情况
                Log.e("WeatherView", "Received null WeatherInfo");
            }
        });

        viewModel.getCurrentAQI().observe(this, post -> {
            if (post != null) {
                // 更新视图
                aqi_tv.setText(post.getNow().getAqi());
                aqi_cond_tv.setText(post.getNow().getCategory());
                pgb.setProgress(Integer.parseInt(post.getNow().getAqi()));

            } else {
                // 处理错误情况
                Log.e("WeatherView", "Received null WeatherInfo");
            }
        });

        geo_viewModel.getCityInfo().observe(
                this, post -> {
                    if (post != null) {
                        String info = post.getLocation().get(0).getAdm2();
                        city_tv.setText(info);
                        test.setText("");
                        Log.e("CITY", info);
                    } else {
                        Log.e("WeatherView", "Received null CityInfo");
                    }
                }
        );

        /*
         * 注册一个能够点击跳转到天气圈功能的floatingActionButton
         */
        weathergram_fab.setOnClickListener(v->{
            Intent intent = new Intent(getApplication(), DiaryActivity.class);
            startActivity(intent);
        });

    }

    // 请求获准定位服务权限
    private void requestLocationPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // Permission is not granted, request it
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION_PERMISSION);
        } else {
            // Permission has already been granted
            initLocationClient();
        }
    }

    // 获准启用精确位置后开始定位
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_LOCATION_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission granted
                initLocationClient();
            } else {
                // Permission denied
                Toast.makeText(this, "需要定位权限才能使用此功能", Toast.LENGTH_SHORT).show();
            }
        }
    }

    // 启动高德地图定位api
    private void initLocationClient() {
        try {
            locationClient = new AMapLocationClient(getApplicationContext());

            // 设置定位参数，如高精度、一次定位还是持续定位等
            option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            option.setInterval(5000);
//            option.setOnceLocationLatest(true);
            locationClient.setLocationOption(option);
            locationClient.setLocationListener(amapLocation -> {
                runOnUiThread(() -> {
                    if (amapLocation != null) {
                        if (amapLocation.getErrorCode() == 0) {
                            // 定位成功，获取经纬度等信息
                            double latitude = amapLocation.getLatitude();
                            double longitude = amapLocation.getLongitude();

                            Log.e("LOCATE_AMAP", String.format(Locale.getDefault(), "%.6f, %.6f", latitude, longitude));

                            DecimalFormat df = new DecimalFormat("#");
                            String formattedLatitude = df.format(latitude);
                            String formattedLongitude = df.format(longitude);
                            String locate = formattedLongitude + "," + formattedLatitude;

                            if(locate.equals(old_locate)){
//                                Toast.makeText(this,"not", Toast.LENGTH_SHORT).show();
                            }
                            else {
                                viewModel.setLocation(locate);
                                geo_viewModel.setLocation(locate);
                                old_locate = locate;
//                                Toast.makeText(this,"locating", Toast.LENGTH_SHORT).show();
                            }



                            if (aqi_map_url == null) {
                                // 设置空气质量地图
                                aqi_map_url = "https://map.qweather.com/index.html?" + "lat=" + formattedLatitude + "&" + "lon=" + formattedLongitude + "&" + "level=" + "8" + "&" + "layer=pm2p5";

                                aqi_map.loadUrl(aqi_map_url);

                                // 确保网页加载完成后滚动到中间
                                aqi_map.setWebViewClient(new WebViewClient() {
                                    @Override
                                    public void onPageFinished(WebView view, String url) {
                                        super.onPageFinished(view, url);

                                        // 执行滚动
                                        aqi_map.scrollTo(0, 100);
                                    }
                                });
                            }

                        } else {
                            // 定位失败，处理错误
                            String errorMsg = "定位失败," + amapLocation.getErrorInfo();
                            Log.e("AmapError", errorMsg);
                        }
                    }
                });
            });

            // 启动定位
            locationClient.startLocation();
        } catch (Exception e) {
            Log.e("WeatherForecast", "Can't start Location");
        }
    }

}